﻿/************************************************************************************
 *      Copyright (C) 2008 greenwx.com,All Rights Reserved						    *
 *      File:																		*
 *				SerializationHelper.cs                                     			*
 *      Description:																*
 *				序列化配置类           	   										    *
 *      Author:																		*
 *				yuh 														        *
 *				yuh@greenwx.com 													*
 *				http://www.cnkker.com												*
 *      Finish DateTime:															*
 *				2008年11月6日       												*
 *      History:																	*
 ***********************************************************************************/
using System;
using System.IO;
using System.Xml.Serialization;

namespace Yu.Cms.Config
{
    /// <summary>
    /// SerializationHelper
    /// </summary>
    public class SerializationHelper
    {
        private SerializationHelper()
        {
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="filename">文件路径</param>
        /// <returns></returns>
        public static object Load(Type type, string filename)
        {
            FileStream fs = null;
            try
            {
                // open the stream...
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }


        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filename">文件路径</param>
        public static bool Save(object obj, string filename)
        {
            bool sucess = false;
            FileStream fs = null;
            // serialize it...
            try
            {
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(fs, obj);
                sucess = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return sucess;
        }
    }
}
